<template>
  <div class="test-api-container">
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <h2>API 测试页面</h2>
          <el-tag type="success">使用 Mock 数据进行测试</el-tag>
        </div>
      </template>

      <!-- 认证测试 -->
      <el-collapse v-model="activeNames">
        <el-collapse-item title="认证模块测试" name="auth">
          <div class="test-section">
            <h3>用户登录</h3>
            <el-form :model="loginForm" label-width="100px" class="test-form">
              <el-form-item label="用户名">
                <el-input v-model="loginForm.username" placeholder="输入用户名" />
              </el-form-item>
              <el-form-item label="密码">
                <el-input v-model="loginForm.password" type="password" placeholder="输入密码" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="testLogin" :loading="loading">测试登录</el-button>
                <el-button @click="testLoginError">测试登录错误</el-button>
              </el-form-item>
            </el-form>
            <div v-if="loginResult" class="result-box">
              <h4>登录结果：</h4>
              <pre>{{ JSON.stringify(loginResult, null, 2) }}</pre>
            </div>
          </div>

          <div class="test-section">
            <h3>发送验证码</h3>
            <el-form :model="codeForm" label-width="100px" class="test-form">
              <el-form-item label="手机号">
                <el-input v-model="codeForm.phoneNumber" placeholder="输入手机号" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="testSendCode" :loading="loading">发送验证码</el-button>
              </el-form-item>
            </el-form>
            <div v-if="codeResult" class="result-box">
              <h4>验证码结果：</h4>
              <pre>{{ JSON.stringify(codeResult, null, 2) }}</pre>
            </div>
          </div>
        </el-collapse-item>

        <!-- 监控测试 -->
        <el-collapse-item title="监控模块测试" name="monitor">
          <div class="test-section">
            <h3>上传环境数据</h3>
            <el-form :model="environmentForm" label-width="100px" class="test-form">
              <el-form-item label="溶解氧">
                <el-input v-model="environmentForm.dissolvedOxygen" type="number" placeholder="溶解氧值" />
              </el-form-item>
              <el-form-item label="水温">
                <el-input v-model="environmentForm.waterTemperature" type="number" placeholder="水温值" />
              </el-form-item>
              <el-form-item label="pH值">
                <el-input v-model="environmentForm.phValue" type="number" placeholder="pH值" />
              </el-form-item>
              <el-form-item label="网箱编号">
                <el-input v-model="environmentForm.netCageId" type="number" placeholder="网箱编号" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="testUploadEnvironment" :loading="loading">上传环境数据</el-button>
                <el-button @click="testUploadEnvironmentError">测试错误数据</el-button>
              </el-form-item>
            </el-form>
            <div v-if="environmentResult" class="result-box">
              <h4>上传结果：</h4>
              <pre>{{ JSON.stringify(environmentResult, null, 2) }}</pre>
            </div>
          </div>

          <div class="test-section">
            <h3>查询环境数据</h3>
            <el-form :model="queryForm" label-width="100px" class="test-form">
              <el-form-item label="网箱编号">
                <el-input v-model="queryForm.netCageId" type="number" placeholder="网箱编号" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="testQueryEnvironment" :loading="loading">查询环境数据</el-button>
              </el-form-item>
            </el-form>
            <div v-if="environmentList.length > 0" class="result-box">
              <h4>环境数据列表：</h4>
              <el-table :data="environmentList" style="width: 100%">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="dissolvedOxygen" label="溶解氧" width="100" />
                <el-table-column prop="waterTemperature" label="水温" width="100" />
                <el-table-column prop="phValue" label="pH值" width="100" />
                <el-table-column prop="netCageId" label="网箱编号" width="100" />
                <el-table-column prop="samplingTime" label="采样时间">
                  <template #default="scope">
                    {{ new Date(scope.row.samplingTime).toLocaleString() }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-collapse-item>

        <!-- 智慧识鱼测试 -->
        <el-collapse-item title="智慧识鱼模块测试" name="recognition">
          <div class="test-section">
            <h3>获取最新识别记录</h3>
            <el-button type="primary" @click="testGetRecentRecords" :loading="loading">获取最新记录</el-button>
            <div v-if="recentRecords.length > 0" class="result-box">
              <h4>最新识别记录：</h4>
              <el-table :data="recentRecords" style="width: 100%">
                <el-table-column prop="username" label="用户" width="100" />
                <el-table-column prop="fishName" label="鱼类" width="100" />
                <el-table-column prop="confidence" label="置信度" width="100">
                  <template #default="scope">
                    {{ (scope.row.confidence * 100).toFixed(1) }}%
                  </template>
                </el-table-column>
                <el-table-column prop="uploadTime" label="上传时间" />
                <el-table-column prop="thumbnail" label="缩略图" width="100">
                  <template #default="scope">
                    <el-image :src="scope.row.thumbnail" style="width: 50px; height: 50px" />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <div class="test-section">
            <h3>获取热榜数据</h3>
            <el-button type="primary" @click="testGetHotRanking" :loading="loading">获取热榜</el-button>
            <div v-if="hotRanking.length > 0" class="result-box">
              <h4>热榜数据：</h4>
              <el-table :data="hotRanking" style="width: 100%">
                <el-table-column prop="fishName" label="鱼类" width="150" />
                <el-table-column prop="searchCount" label="搜索次数" width="120" />
                <el-table-column prop="popularity" label="热度" width="120" />
              </el-table>
            </div>
          </div>
        </el-collapse-item>

        <!-- 鱼病诊断测试 -->
        <el-collapse-item title="鱼病诊断模块测试" name="disease">
          <div class="test-section">
            <h3>健康状态评估</h3>
            <el-form :model="healthForm" label-width="100px" class="test-form">
              <el-form-item label="溶解氧">
                <el-input v-model="healthForm.dissolvedOxygen" type="number" placeholder="溶解氧值" />
              </el-form-item>
              <el-form-item label="水温">
                <el-input v-model="healthForm.waterTemperature" type="number" placeholder="水温值" />
              </el-form-item>
              <el-form-item label="pH值">
                <el-input v-model="healthForm.phValue" type="number" placeholder="pH值" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="testHealthCheck" :loading="loading">健康状态评估</el-button>
              </el-form-item>
            </el-form>
            <div v-if="healthResult" class="result-box">
              <h4>健康状态结果：</h4>
              <el-tag :type="healthResult.healthStatus === 'Healthy' ? 'success' : 'danger'">
                {{ healthResult.healthStatus === 'Healthy' ? '健康' : '异常' }}
              </el-tag>
              <p>{{ healthResult.msg }}</p>
            </div>
          </div>

          <div class="test-section">
            <h3>获取专家列表</h3>
            <el-button type="primary" @click="testGetExpertList" :loading="loading">获取专家列表</el-button>
            <div v-if="expertList.length > 0" class="result-box">
              <h4>专家列表：</h4>
              <el-table :data="expertList" style="width: 100%">
                <el-table-column prop="expertName" label="专家姓名" width="120" />
                <el-table-column prop="title" label="职称" width="100" />
                <el-table-column prop="organization" label="单位" />
                <el-table-column prop="specialtyFish" label="擅长品种" width="120" />
                <el-table-column prop="specialtyDisease" label="擅长疾病" width="120" />
              </el-table>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>

      <!-- WebSocket测试 -->
      <div class="test-section">
        <h3>WebSocket 实时统计</h3>
        <el-button type="primary" @click="connectWebSocket" :loading="wsLoading">连接WebSocket</el-button>
        <el-button type="danger" @click="disconnectWebSocket">断开连接</el-button>
        <div v-if="statisticsData" class="result-box">
          <h4>实时统计数据：</h4>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card>
                <div class="stat-item">
                  <div class="stat-number">{{ statisticsData.onlineUsers }}</div>
                  <div class="stat-label">在线用户</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card>
                <div class="stat-item">
                  <div class="stat-number">{{ statisticsData.todayRecognitions }}</div>
                  <div class="stat-label">今日识别</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card>
                <div class="stat-item">
                  <div class="stat-number">{{ statisticsData.totalRecognitions }}</div>
                  <div class="stat-label">总识别数</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card>
                <div class="stat-item">
                  <div class="stat-number">{{ statisticsData.totalImages }}</div>
                  <div class="stat-label">总图片数</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { mockAuthApi, mockMonitorApi, mockFishRecognitionApi, mockFishDiseaseApi, mockStatisticsWebSocket } from '@/api'

// 响应式数据
const loading = ref(false)
const wsLoading = ref(false)
const activeNames = ref(['auth', 'monitor', 'recognition', 'disease'])

// 表单数据
const loginForm = reactive({
  username: 'test_user',
  password: 'password123'
})

const codeForm = reactive({
  phoneNumber: '13800138000'
})

const environmentForm = reactive({
  dissolvedOxygen: 8.5,
  waterTemperature: 25.0,
  phValue: 7.2,
  netCageId: 1
})

const queryForm = reactive({
  netCageId: 1
})

const healthForm = reactive({
  dissolvedOxygen: 8.5,
  waterTemperature: 25.0,
  phValue: 7.2
})

// 结果数据
const loginResult = ref(null)
const codeResult = ref(null)
const environmentResult = ref(null)
const environmentList = ref([])
const recentRecords = ref([])
const hotRanking = ref([])
const healthResult = ref(null)
const expertList = ref([])
const statisticsData = ref(null)

// 测试登录
const testLogin = async () => {
  loading.value = true
  try {
    const result = await mockAuthApi.login(loginForm)
    loginResult.value = result
    ElMessage.success('登录测试成功')
  } catch (error) {
    ElMessage.error('登录测试失败')
    console.error('登录错误:', error)
  } finally {
    loading.value = false
  }
}

// 测试登录错误
const testLoginError = async () => {
  loading.value = true
  try {
    const result = await mockAuthApi.login({
      username: 'nonexistent',
      password: 'wrongpassword'
    })
    loginResult.value = result
  } catch (error) {
    ElMessage.error('登录失败：' + error.msg)
    console.error('登录错误:', error)
  } finally {
    loading.value = false
  }
}

// 测试发送验证码
const testSendCode = async () => {
  loading.value = true
  try {
    const result = await mockAuthApi.sendCode(codeForm.phoneNumber)
    codeResult.value = result
    ElMessage.success('验证码发送成功')
  } catch (error) {
    ElMessage.error('验证码发送失败：' + error.msg)
    console.error('验证码错误:', error)
  } finally {
    loading.value = false
  }
}

// 测试上传环境数据
const testUploadEnvironment = async () => {
  loading.value = true
  try {
    const result = await mockMonitorApi.uploadEnvironmentData(environmentForm)
    environmentResult.value = result
    ElMessage.success('环境数据上传成功')
  } catch (error) {
    ElMessage.error('环境数据上传失败：' + error.msg)
    console.error('上传错误:', error)
  } finally {
    loading.value = false
  }
}

// 测试上传错误数据
const testUploadEnvironmentError = async () => {
  loading.value = true
  try {
    const result = await mockMonitorApi.uploadEnvironmentData({
      dissolvedOxygen: -1,
      waterTemperature: 100,
      phValue: 20,
      netCageId: 1
    })
    environmentResult.value = result
  } catch (error) {
    ElMessage.error('环境数据上传失败：' + error.msg)
    console.error('上传错误:', error)
  } finally {
    loading.value = false
  }
}

// 测试查询环境数据
const testQueryEnvironment = async () => {
  loading.value = true
  try {
    const result = await mockMonitorApi.getEnvironmentDataList(queryForm)
    environmentList.value = result.data || []
    ElMessage.success('环境数据查询成功')
  } catch (error) {
    ElMessage.error('环境数据查询失败')
    console.error('查询错误:', error)
  } finally {
    loading.value = false
  }
}

// 测试获取最新识别记录
const testGetRecentRecords = async () => {
  loading.value = true
  try {
    const result = await mockFishRecognitionApi.getRecentRecords()
    recentRecords.value = result.data || []
    ElMessage.success('获取最新识别记录成功')
  } catch (error) {
    ElMessage.error('获取最新识别记录失败')
    console.error('获取记录错误:', error)
  } finally {
    loading.value = false
  }
}

// 测试获取热榜
const testGetHotRanking = async () => {
  loading.value = true
  try {
    const result = await mockFishRecognitionApi.getHotRanking()
    hotRanking.value = result.data || []
    ElMessage.success('获取热榜成功')
  } catch (error) {
    ElMessage.error('获取热榜失败')
    console.error('获取热榜错误:', error)
  } finally {
    loading.value = false
  }
}

// 测试健康状态评估
const testHealthCheck = async () => {
  loading.value = true
  try {
    const result = await mockFishDiseaseApi.healthCheck(healthForm)
    healthResult.value = result
    ElMessage.success('健康状态评估完成')
  } catch (error) {
    ElMessage.error('健康状态评估失败')
    console.error('健康检查错误:', error)
  } finally {
    loading.value = false
  }
}

// 测试获取专家列表
const testGetExpertList = async () => {
  loading.value = true
  try {
    const result = await mockFishDiseaseApi.getExpertList()
    expertList.value = result.data || []
    ElMessage.success('获取专家列表成功')
  } catch (error) {
    ElMessage.error('获取专家列表失败')
    console.error('获取专家列表错误:', error)
  } finally {
    loading.value = false
  }
}

// WebSocket连接
const connectWebSocket = () => {
  wsLoading.value = true
  mockStatisticsWebSocket.onMessage = (data) => {
    statisticsData.value = data.data || {}
  }
  mockStatisticsWebSocket.connect()
  ElMessage.success('WebSocket连接成功')
  wsLoading.value = false
}

// WebSocket断开
const disconnectWebSocket = () => {
  mockStatisticsWebSocket.disconnect()
  statisticsData.value = null
  ElMessage.info('WebSocket连接已断开')
}

// 组件卸载时断开WebSocket
onUnmounted(() => {
  mockStatisticsWebSocket.disconnect()
})
</script>

<style scoped>
.test-api-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
}

.test-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
}

.test-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #409eff;
  border-bottom: 2px solid #409eff;
  padding-bottom: 5px;
}

.test-form {
  max-width: 500px;
}

.result-box {
  margin-top: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.result-box h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.result-box pre {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 12px;
  line-height: 1.4;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.el-collapse-item {
  margin-bottom: 10px;
}
</style> 